#include "stdafx.h"
#include "ConnectionManager.h"

void CConnectionManager::getInfo(const ConnectionParameter * param)
{
	if (INVALID_SOCKET == param->ServerSocket)return;
	//if(strcmp(param->UrlData->HostName.c_str(),"fhzd.org")==0)
	SocketInfo si(param->ServerSocket);
	PRINTF("%-20s\tC:%-8dS:%-8d %s\n", param->UrlData->HostName.c_str(), param->ClientSocket, param->ServerSocket, si.toString().c_str());
}

CConnectionManager::CConnectionManager()
{
	InitializeCriticalSection(&cs);
}


CConnectionManager::~CConnectionManager()
{
	DeleteCriticalSection(&cs);
}

void CConnectionManager::add(ConnectionParameter* p)
{
	EnterCriticalSection(&cs);
	m_ClientList.insert(p);
	LeaveCriticalSection(&cs);
}

void CConnectionManager::remove(ConnectionParameter* param)
{

	if (m_ClientList.empty())return;
	EnterCriticalSection(&cs);

	CloseHandle(param->ThreadHandle);
	param->ThreadHandle = INVALID_HANDLE_VALUE;

	m_ClientList.erase(param);
	delete param;
	param = nullptr;

	LeaveCriticalSection(&cs);
}

void CConnectionManager::removeAll() {
	EnterCriticalSection(&cs);

	CLIENTLIST::const_iterator iter = m_ClientList.begin();
	while (iter != m_ClientList.end())
	{
		ConnectionParameter * param = *iter;
		param->CloseSocketAll();

		if (INVALID_HANDLE_VALUE != param->ThreadHandle)
			CloseHandle(param->ThreadHandle);

		delete param;
		param = nullptr;
		++iter;
	}

	m_ClientList.clear();
	LeaveCriticalSection(&cs);
}


void CConnectionManager::Disconnect()
{
	EnterCriticalSection(&cs);

	CLIENTLIST::const_iterator iter = m_ClientList.begin();
	while (iter != m_ClientList.end())
	{
		ConnectionParameter * param = *iter;
		param->CloseSocketAll();
		++iter;
	}

	LeaveCriticalSection(&cs);
}

void CConnectionManager::ShowAll()
{
	//system("cls");
	PRINTF("ShowAll:begin\n");
	for_each(m_ClientList.begin(), m_ClientList.end(), CConnectionManager::getInfo);
	PRINTF("ShowAll:end.size:%d\n", m_ClientList.size());
	
	
	
	
	int pid = _getpid();
	char szID[12] = { 0 };
	_itoa_s(pid, szID, 10);
	string s;
	s.append("netstat -aon|findstr ");
	s.append(szID);
	system(s.c_str());
	
}
